<template>
	<!-- 系统目录 卫材 -->
	<div class="box">
		<!-- main -->
		<div class="main">
			<!-- left -->
			<div class="main-left">
				<!-- tree -->
				<el-tree
				:data="elTree"
				v-loading="loading"
				element-loading-spinner="el-icon-more-outline"
				:props="defaultProps"
				node-key="label"
				:default-expanded-keys="['全部']"
				accordion
				@node-click="handleNodeClick"
				class="custom-tree"
				>
					<span class="custom-tree-node" slot-scope="{ node, data }" style="font-size: 12px;">
						<span :name="node.label">
							<i v-if="!data.children"
							:class="node.expanded ? 'el-icon-openFile' : 'el-icon-closeFiles'"></i>
							<i v-else class="el-icon-openFile"></i>{{ node.label }}
						</span>
					</span>
				</el-tree>
			</div>
			<!-- right -->
			<div class="main-right" ref="mainRight">
				<!-- tit -->
				<div class="main-icon">
					<div class="main-icon-a">
						<i :class="iconComes" style="border-radius: 50%;font-size: 20px;padding: 6px;margin-left: 8px;;background-color: #00557f;color: #fff;"></i>
						<span style="font-size: 12px;font-weight:bold;margin-left: 12px;color: #606266;">{{ CatalogueName }}</span>
					</div>
					<!-- btn1 -->
					<div class="main-icon-b">
						<span style="font-size: 12px;color: #606266;font-weight: bold;">状态：</span>
						<el-dropdown @command="handleCommand" trigger="click">
							<span class="el-dropdown-link">{{ DropDownedName }}<i class="el-icon-down"></i></span>
							<el-dropdown-menu slot="dropdown">
							  <el-dropdown-item command="a">可用</el-dropdown-item>
							  <el-dropdown-item command="b">禁用</el-dropdown-item>
							  <el-dropdown-item command="c" divided>全部</el-dropdown-item>
							</el-dropdown-menu>
					    </el-dropdown>
					</div>
					<!-- btn2 -->
					<div class="main-icon-c">
						<span style="font-size: 12px;color: #606266;font-weight: bold;display: inline-block;width: 68px;">关键字：</span>
						<el-input size="mini" placeholder="编码、名称、拼音简码" suffix-icon="el-icon-key" v-model="searchValue"></el-input>
					</div>
					<!-- btn3 -->
					<div class="main-icon-c">
						<el-button v-for="(v,i) in headerBtn" :key="i" :type="v.type" :loading="loading" :icon="v.icon" size="mini" @click="handClick(i)">{{ v.title }}</el-button>
					</div>
				</div>
				<!-- table -->
				<div class="table">
					<el-table :data="tableData" border @row-dblclick="handledbRow"
					element-loading-text="查询中" v-loading="loading" element-loading-spinner="el-icon-more-outline"
					highlight-current-row @current-change="handleCurrentTableChange" ref="singleTable">
						<el-table-column v-for="(col, inx) in tableRows" :key="inx" :type="col.type" :prop="col.prop" :label="col.name" :width="columnWidth(col, tableData)"></el-table-column>
						<!-- fixed -->
						<el-table-column fixed="left" label="行号" type="index"></el-table-column>
						<!-- edit -->
						<el-table-column fixed="right" label="操作" width="148">
						      <template slot-scope="scope">
								  <div class="editbox" style="text-align: center;">
									<el-button type="primary" @click="handleClickEdit(scope.row)" size="mini">编辑</el-button>
									<el-button type="danger" @click="handleDelete(scope.row.id)" size="mini">删除</el-button>
								  </div>
						      </template>
						</el-table-column>
					</el-table>
					<!-- 分页 -->
					<el-pagination
						@size-change="handleSizeChange"
						@current-change="handleCurrentChange"
						:current-page="pageNum"
						:page-sizes="[8, 16, 24]"
						:page-size="pageSize"
						:total="totalSize"
						layout="total, sizes, prev, pager, next, jumper"
						background>
					</el-pagination>
				</div>
				<!-- feet -->
				<div class="feet" id="feet">
					<div class="feetBtn">
						<el-button v-for="(v,i) in feetBtn" :key="i" :type="v.type" :loading="loading" :icon="v.icon" size="mini" @click="feetHandClick(v,i)">{{ v.title }}</el-button>
					</div>
				</div>
			</div>
		</div>
		<!-- add data 新增等model -->
		<div class="addmessagesBox">
			<addCharing ref='sonRef' :parent-method="loadData"></addCharing>
		</div>
		<!-- add data 修改 model -->
		<div class="edutmessagesBox">
			<editCharing ref='soneditRef' :parent-method="loadData"></editCharing>
		</div>
	</div>
</template>/

<script>
// selfs / js
import AccType from './AddType.js'
import editType from './editType.js'
// import addForm from './addForm.js'
// selfs / props
import addCharing from './addCharing.vue'
import editCharing from './editCharing.vue'
// 接口
import { getCostList,getCostType,deleteByItemId } from "@/api/Outpatient/category.js";

	export default {
		inject: ['reload'], // 无痕刷新
		components: {
			addCharing,editCharing
		},
		data() {
			return {
				defaultProps: {
					children: 'children',
					label: 'label'
				},
				// str
				windowWidth:'', //右侧表格动态宽度
				searchValue:'',
				iconHandleClick:'el-icon-charging',
				CatalogueName:'卫材目录',
				DropDownedName:'可用',
				iconComes:'el-icon-charging',
				operatingTime:'',
				// boolean
				loading:false,
				// number
				pageNum: 1, //当前页currentPage
				pageSize: 8,
				totalSize: 10, //总条数
				/* obj */
				// 新增
				addForm: {},
				// arr
				data: [],
				oop:[],
				userInfo: [],
				// 新增表单自定义格式
				formType:[],
				// title右侧按钮
				headerBtn:[
				 { refesh:"refesh", title:"刷新", type:"", icon:"el-icon-refresh" },
				 { senior:"senior", title:"高级", type:"", icon:"" },
				],
				// 页面默认按钮// 基础按钮配置（始终显示）
				defaultButtons:[
					// { title:"新增",icon:"el-icon-adds", type:"primary" },
					// { title:"修改",icon:"el-icon-edit", type:"primary" },
					{ title:"查看",icon:"el-icon-watch", type:"primary" },
					{ title:"删除",icon:"el-icon-del", type:"danger" },
					// { title:"目录引用",icon:"el-icon-closeFiles", type:"primary" },
					{ title:"打印",icon:"el-icon-ggml", type:"primary" },
					{ title:"导出",icon:"el-icon-export", type:"primary" },
					{ title:"关闭",icon:"el-icon-close", type:"primary" },
				],
				// 最终使用的按钮数组
				feetBtn: [],
				currentTable:[],
				// title右侧按钮
				tableRows:[
					{ name:"系统序号", prop:"id", type:"" },{ name:"编码", prop:"state", type:"" },
					{ name:"名称", prop:"chargeProjectName", type:"" },{ name:"别名", prop:"projectConnotation", type:"" },
					{ name:"计费范围", prop:"description", type:"" },{ name:"规格描述", prop:"measurementUnit", type:"" },
					{ name:"包装单位", prop:"coding", type:""},{ name:"包装数量", prop:"priceCode", type:"" },
					{ name:"剂量单位", prop:"id", type:"" },{ name:"生产厂家", prop:"state", type:"" },
					{ name:"卫材种类", prop:"coding", type:""},{ name:"物价编码", prop:"priceCode", type:"" },
					{ name:"卫材属性", prop:"chargeProjectName", type:"" },{ name:"有效状态", prop:"projectConnotation", type:"" },
					{ name:"内置否", prop:"description", type:"" },{ name:"操作时间", prop:"operatingTime", type:"" },
					{ name:"操作人", prop:"operatingPeople", type:"" },{ name:"备注", prop:"remake", nz:"nz" },
					{ name:"限定用药", prop:"standardName", type:"" },{ name:"国家贯标编码", prop:"standardCode", type:"" },
				],
				elTree:[{label: '全部',icon:'el-icon-news',children:[]}],
				tableData: [
					{ num:'1', code:'01',name:'预防保健科',nz:'否', status: '可用',remark:'' },
					{ num:'2', code:'02',name:'全科医疗科',nz:'否', status: '可用',remark:'' },
					{ num:'3', code:'03',name:'内科',nz:'否', status: '可用',remark:'' },
					{ num:'4', code:'04',name:'消化内科专业',nz:'否', status: '可用',remark:'' },
					{ num:'5', code:'05',name:'神经内科专业',nz:'否', status: '可用',remark:'' },
					{ num:'6', code:'06',name:'心血管内科专业',nz:'否', status: '可用',remark:'' },
				],
				pickerOptions: {
				  shortcuts: [
					{ text: '今天', onClick(picker) { picker.$emit('pick', new Date()); }},
					{ text: '昨天', onClick(picker) { const date = new Date();date.setTime(date.getTime() - 3600 * 1000 * 24);picker.$emit('pick', date);}},
					{ text: '一周前',onClick(picker) {const date = new Date();date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);picker.$emit('pick', date);}},
					]
				},
			};
		},
		computed: {
		    // 格式化数字，确保4个0后的数字自增时不会出现前导零
		    formattedNumber() {
				return '00000' + this.toCodeNum.toString().slice(1);
		    },
		  },
		mounted() {
			this.loadData();
			//获取动态盒子宽度，实时赋值给右侧 => this.$refs.mainRight.offsetWidth;
			this.$nextTick(()=>{
				this.updateWindowWidth();
				window.addEventListener('resize', this.updateWindowWidth);
				this.initButtons(); // 引入全局自定义封装方法
			})
			this.getAllTree();
			this.userInfo = JSON.parse(localStorage.getItem('userInfo'));
			this.addForm.operator = this.userInfo.userName
		},
		methods: {
			/*
				about tree
			*/
		    async getAllTree(){
			   let res = await getCostType();
			   this.elTree[0].children.push(...res.data.map(v=>{ return { label: v.name , ...v } }));
			   console.log(this.elTree);
		    },
			handleNodeClick(data,e) {
				this.loading = true;//关闭加载
				this.addForm.expenseCategoryId = data.label
				this.CatalogueName = data.label
				// this.iconComes = 'el-icon-' + this.makePy(data.label)
				console.log(data);
				this.loadData();
			},
			initButtons() {
			    // 获取当前路由路径
			    const currentPath = this.$route.path;
			    // 获取路由对应的权限按钮
			    const routeButtons = this.$getRouteButtons(currentPath);
			    console.log(routeButtons,'routeButtonsrouteButtons');
			    // 合并到现有按钮数组
			    this.feetBtn = this.$mergeButtons(this.defaultButtons, routeButtons);
				console.log(this.feetBtn,'this.feetBtnthis.feetBtn');
			},
			/*
				about table
			*/

		   // 数据源 毒麻类型
		    async loadData(){
				let res = await getCostList({
					pageNum: this.pageNum,
					pageSize: this.pageSize,
					costType: this.CatalogueName,
					chargeProjectName:this.searchValue
				})
				if(res.data){
					this.tableData = res.data.content
					this.$message({
					  message: '已为您查询到' + res.data.totalSize + '条数据.',
					  type: 'success'
					});
					this.tableData = res.data.content;
					this.totalSize = res.data.totalSize;
					this.pageSize = res.data.pageSize
					this.loading = false;
				}else{
					this.tableData = [];
					this.$message.error(res.message)
					this.loading = false;
				}
		    },
		    // col 里面包含了表头字段和名称，list 是表格数据
		    columnWidth(col, list) {
		         let prop = col.prop,lab = col.lab;
		         let width = 40; // 设定一个最小值
		         let maxlenStr = ""; // 最长字符串
		         for (let info of list) {
		           if (maxlenStr < (info[prop] + "").length) maxlenStr = info[prop];
		         }
		         width = Math.max(width, len(lab), len(maxlenStr));
		         // 表格自带的内边距(20px) 自调
		         return width + 28; // 这里加了 12px
		         function len(str) {
		           // 实际分配长度可根据需要自行调整
		           let length = 8;
		           for (const char of str + "") {
		             // 英文小写字符 8px
		             if ("a" <= char && char <= "z") length += 12;
		             // 英文大写字符 8px
		             else if ("A" <= char && char <= "Z") length += 8;
		             // 中文字符 28px
		             else if (char >= "\u4e00" && char <= "\u9fa5") length += 28;
		             // 其他 8px
		             else length += 12;
		           }
		           return length;
		         }
		    },
			// see table
			// 取消高亮
			setCurrent(row) {
			    this.$refs.singleTable.setCurrentRow(row);
			},
			// edit table
			handleClickEdit(row){
				this.editChargingVisible = true;
				this.editForm = { ...row };
			},
			// del table
			handleDelete(id){
				this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				type: "warning",
				})
				.then(async() => {
				let res = await deleteByItemId({ id });
				if (res.code == 200) {
					this.$message({ type: "success", message: '已删除' });
					this.loadData(); //重新加载数据页面
				} else {
					this.$message({ type: "error", message: 'fail' });
				}
				}).catch(() => {
					this.$message({ type: "warning", message: '已取消删除' });
				});
			},
			// db events
			handledbRow(row, column, event){
				if(row){ this.form = row; this.dialogVisible = true } else { console.log('fail'); }
				// console.log(this.form);
				this.formdisabled = true
				this.form.textSpell = this.makePy(this.form.label).toLocaleUpperCase()
				// console.log(this.form.textSpell);
			},
			// 表格单选
			handleCurrentTableChange(val){
				this.currentTable = val
			},
			// 表格权限动态循环按钮事件
			feetHandClick(v){
				// v event
				if(v.label == '新增'){
					// => 新增 => 调用子组件方法
					this.$refs.sonRef.open()
				}else if(v.label == '修改'){
					// => 修改 => 调用子组件方法
					if(this.currentTable.length === 0){
						this.$message({ type: 'warning', message: '请先单击选择一条数据'});
					}else{
						this.$refs.soneditRef.open(this.currentTable)
					}
				}else{
					this.$message({ type: 'error', message: '开发完善中...!'});
				}
			},
			// 步骤
			handClick(i) {
				// i event
				switch (i) {
					case 0:
						this.loading = true;
						setTimeout(() => {
							this.reload();
							this.$message({type:'success',message:'已刷新'})
							this.loading = false;
						}, 1500)
						break;
					case 1:
						// 处理索引1的逻辑
						this.$confirm('敬请期待')
							.then(_ => {})
							.catch(_ => {});
						break;
				}
			},
			//状态数据
			handleCommand(command) {
			console.log(command);
			// 根据 command 值执行相应的逻辑

			},
			//分页
			//每页条数改变触发
			handleSizeChange(val) {
				console.log(`每页 ${val} 条`);
				this.pageSize = val;
				this.pageNum = 1;
				this.loadData();
			},
			//当前条数改变触发
			handleCurrentChange(val) {
				console.log(`当前页: ${val}`);
				this.pageNum = val;
				this.loadData();
			},
			// 实时宽度
			updateWindowWidth() {
			    this.windowWidth = window.innerWidth - 368;
			},
			// 系统当前日期时间
			nowDateTime(){
				const now = new Date(); //创建时间日期对象
				const year = now.getFullYear(); //年
				const month = now.getMonth() + 1; //月份是从0开始的
				const day = now.getDate(); //日
				const hours = now.getHours(); //小时
				const minutes = now.getMinutes(); //分钟
				const seconds = now.getSeconds(); //秒
				const currentDate = `${year}-${month}-${day}`.replace(/-/g, '') //替换操作
				this.nowDateTimeValue = `${year}-${month}-${day}` + ` ` + `${hours}:${minutes}:${seconds}`
				// this.datetimesinglend =
				// 将字符串转换为Date对象
				// console.log(this.nowDateTimeValue);
			}

		}
	}
</script>


<style lang="less" scoped>
	.box {
	  height: calc(100vh - 64px); // 减去导航栏高度
	  width: 100%;
	  overflow: hidden;
	/deep/ .el-table .cell{
		font-size: 12px;
		text-overflow: ellipsis;
		white-space: nowrap;
		overflow: hidden;
	}
	/deep/ .el-table th{
		font-size: 12px;
		background-color: #f1f1f1;
		border: none;
		color: #2d2d2d;
	}
	/deep/ .el-table {
	    width: 100%;
	    height: 100% !important;
	    .el-table__body-wrapper {
	      overflow-x: hidden;
	    }
	}
	/* 自定义高亮颜色 */
	::v-deep .el-table__body tr.current-row > td {
	  background-color: #00557f !important;
	  color: #f9f9f9; /* 可选：修改文字颜色 */
	}
	  .main {
	    display: flex;
	    height: 100%;
	    width: 100%;
	
	    // 左侧树形菜单
	    .main-left {
	      width: 128px;
	      height: 100%;
	      background: #f5f7fa;
	      border-right: 1px solid #e6e6e6;
	      overflow-y: auto;
	      scrollbar-width: none; /* Firefox */
	      -ms-overflow-style: none; /* IE 10+ */
	      
	      &::-webkit-scrollbar {
	        display: none; /* Chrome Safari */
	      }
	
	      /deep/ .el-tree {
	        height: 100%;
	        .el-tree-node__content {
	          height: 36px;
	        }
	      }
	    }
	    
	    // 右侧内容区域
	    .main-right {
	      flex: 1;
	      display: flex;
	      flex-direction: column;
	      height: 100%;
	      overflow: hidden;
	      
	      // 顶部搜索区域
		.main-icon {
			display: flex;
			align-items: center;
			padding: 12px;
			line-height: 40px;
			.main-icon-a{
				// width: 240px;
				// background-color: #00557f;
			}
			.main-icon-b{
				margin-left: 28px;
				/deep/ .el-dropdown{
					font-size: 12px;
					cursor: pointer;
				}
				/deep/ .el-dropdown:hover {
					font-weight: bold;
					color: #66b1ff;
				}
				/deep/ .el-icon--right{
					// background-color: #66b1ff;
				}
				/deep/ .el-popper[x-placement^=bottom]{
					margin-top: 0;
				}
			}
			// c
			.main-icon-c{
				display: flex;
				margin-left: 28px;
				/deep/ [data-v-2bacc09b] .el-color-picker__icon, .el-input[data-v-2bacc09b], .el-textarea[data-v-2bacc09b]{
					width: 80%;
				}
			}
		}
	      
	      // 表格容器（带滚动）
	      .table {
	        flex: 1;
			width: 100%;
	        overflow: hidden;
	        display: flex;
	        flex-direction: column;
			/deep/ .el-pagination {
				margin: 12px;
			}
	    }
	      
	      // 底部固定区域
	      .feet {
	        height: 40px;
	        display: flex;
			align-items: center;
	        padding: 12px;
	        background: #fff;
	        border-top: 1px solid #e6e6e6;
	        flex-shrink: 0;
	        
	        .feetBtn {
	          gap: 8px;
	        }
			
	        }
	    }
	  }
		
		.addModel{
			/deep/ .el-dialog__header{
				padding: 12px;
				line-height: 28px;
				background-color: #007bb0;
			}
			/deep/ .el-dialog__title{
				color: #fff;
				font-size: 12px;
			}
			/deep/ .el-dialog__headerbtn .el-dialog__close{
				color: #fff;
			}
			/deep/ .el-dialog__headerbtn .el-dialog__close:hover{
				background-color: brown;
			}
			/deep/ .el-form-item__label{
				font-size: 12px;
			}
		}
		.editModel{
			/deep/ .el-dialog__header{
				padding: 12px;
				line-height: 28px;
				background-color: #007bb0;
			}
			/deep/ .el-dialog__title{
				color: #fff;
				font-size: 12px;
			}
			/deep/ .el-dialog__headerbtn .el-dialog__close{
				color: #fff;
			}
			/deep/ .el-dialog__headerbtn .el-dialog__close:hover{
				background-color: brown;
			}
			/deep/ .el-form-item__label{
				font-size: 12px;
			}
		}
	}

</style>